fs = require 'fs'
_ = require 'lodash'
del = require 'del'

nib = require 'nib'
gulp = require 'gulp'
rename = require 'gulp-rename'
uglify = require 'gulp-uglify'

pug =  require 'gulp-pug'
coffee = require 'gulp-coffee'
stylus = require 'gulp-stylus'
plumber = require 'gulp-plumber'
minifycss = require 'gulp-minify-css'

html2js_ext  = require './html2js_ext'
handleErrors = require './handle_error'

pug_src = 'src/**/*.pug'
tpl_src = 'src/mods/**/*.pug'

stylus_src = 'src/**/*.styl'
coffee_src = 'src/**/*.coffee'

static_array = [
  'src/**/*.js'
  'src/**/*.tpl'
  'src/**/*.png'
  'src/**/*.jpg'
  'src/**/*.gif'
  'src/**/*.map'
  'src/**/*.ico'
  'src/**/*.css'
  'src/**/*.html'
  'src/**/*.eot'
  'src/**/*.svg'
  'src/**/*.ttf'
  'src/**/*.woff'
  'src/**/*.json'
]

compile_array = [coffee_src, pug_src, stylus_src]
new_array = _.concat compile_array, static_array

gulp.task 'scripts', () ->
  gulp.src coffee_src
    .pipe plumber
      errorHandler: handleErrors
    .pipe coffee()
    # .pipe uglify {mangle:{except : ['$', 'require', 'exports', 'module']}}
    .pipe gulp.dest 'dest'

gulp.task 'html', () ->
  gulp.src pug_src
    .pipe plumber
      errorHandler: handleErrors
    .pipe pug()
    .pipe gulp.dest 'dest'

gulp.task 'html2js', () ->
  gulp.src tpl_src
    .pipe plumber
      errorHandler: handleErrors
    .pipe pug()
    .pipe rename (currPath) ->
      currPath.dirname = "./mods/#{currPath.dirname}"
      currPath.extname = ".js"
      return currPath
    .pipe html2js_ext 'html2js_ext'
    .pipe uglify {mangle:{except : ['$', 'require', 'exports', 'module']}}
    .pipe gulp.dest 'dest'

gulp.task 'css', () ->
  gulp.src stylus_src
    .pipe plumber
      errorHandler: handleErrors
    .pipe stylus {error: true, use: [nib()]}
    .pipe minifycss()
    .pipe gulp.dest 'dest'

gulp.task 'minifycss', () ->
  gulp.src static_array[4]
    .pipe minifycss()

gulp.task 'copy', () ->
  gulp.src static_array
    .pipe gulp.dest 'dest'

gulp.task 'clean', (cb) ->
  del ['dest'], cb

gulp.task 'watch',  () ->
  gulp.watch new_array, ['scripts', 'html', 'html2js', 'css',  'copy']

gulp.task 'default', ['clean'], () ->
  gulp.start 'scripts', 'html', 'html2js', 'css',  'copy', 'watch'